package com.spi.config;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class MyWebSocketHandler extends TextWebSocketHandler {

    //存储所有连接的websocket会话
    private static final ConcurrentHashMap<String, WebSocketSession> sessions = new ConcurrentHashMap<>();

    //当websocket建立连接时 将会话添加到sessions中
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        sessions.put(session.getId(), session);
    }

    //处理前端发送的信息
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String payload = message.getPayload();
        if ("getSessionId".equals(payload)) {
            //String sessionId = UUID.randomUUID().toString();
            String sessionId = session.getId();
            session.sendMessage(new TextMessage("sessionId:" + sessionId));
        }
    }

    //当websocket连接关闭时，移除该会话
    @Override
    public void afterConnectionClosed(WebSocketSession session, org.springframework.web.socket.CloseStatus status) throws Exception {
        sessions.remove(session.getId());
    }

    //遍历所有会话 向所有打开的会话发送消息
    public static void sendMessageToClient(String sessionId, String message) {
        for (Map.Entry<String, WebSocketSession> entry : sessions.entrySet()) {
            WebSocketSession s = entry.getValue();
            if (!s.getId().equals(sessionId)) {
                //判断请求携带的sessionid与本次循环的sessionid是否一致 不一致循环下一个id
                continue;
            }
            if (s.isOpen()) {
                try {
                    s.sendMessage(new TextMessage(message));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
